package com.malex.mxtracker;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Manusovich Alexander
 */
public class MxTrackerUpdater extends Service {
    private Timer timer = new Timer();
    private static final long UPDATE_INTERVAL = 5000;
    public static ServiceUpdateUIListener UI_UPDATE_LISTENER;
    private ConnectivityManager connMan;

    public static void setUpdateListener(ServiceUpdateUIListener l) {
        UI_UPDATE_LISTENER = l;
    }

    public static ServiceUpdateUIListener getUIListener() {
        return UI_UPDATE_LISTENER;
    }

    /**
     * not using ipc... dont care about this method
     */
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        connMan = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        // init the service here
        _startService();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        _shutdownService();
    }

    private void _startService() {
        timer.scheduleAtFixedRate(
                new TimerTask() {
                    public void run() {
                        _getWeatherUpdate();
                    }
                },
                0,
                UPDATE_INTERVAL);
        Log.i(getClass().getSimpleName(), "Timer started!!!");
    }

    private void _getWeatherUpdate() {
        // http post to the service
//        Log.i(getClass().getSimpleName(), "background task - start");
        boolean connected = (connMan.getActiveNetworkInfo() != null && connMan
                .getActiveNetworkInfo().isConnected());
        if (getUIListener() != null) {
            getUIListener().updateUI(connected);
        }
//        Log.i(getClass().getSimpleName(), "background task - end");
    }

    private void _shutdownService() {
        if (timer != null) timer.cancel();
        Log.i(getClass().getSimpleName(), "Timer stopped!!!");
    }
}
